<template>
  <div class="d-paner d-paner-noborder">
    <div class="d-paner-body">
      <table class="d-table d-table-striped d-table-bordered">
        <colgroup>
          <col width="60">
          <col width="120">
        </colgroup>
        <thead>
          <tr>
            <th>序号</th>
            <th>元素</th>
            <th>数量</th>
          </tr>
        </thead>
        <tbody>
          <tr>
            <td>{{ 1 }}</td>
            <td>{{ '字符总计' }}</td>
            <td>{{ state.html }}</td>
          </tr>
          <tr>
            <td>{{ 2 }}</td>
            <td>{{ '文本总计' }}</td>
            <td>{{ state.text }}</td>
          </tr>
          <tr>
            <td>{{ 3 }}</td>
            <td>{{ '元素总计' }}</td>
            <td>{{ state.total }}</td>
          </tr>
        </tbody>
        <tbody>
          <tr v-for="(item, i) in state.list" :key="item.tagName">
            <td>{{ i + 4 }}</td>
            <td>{{ item.tagName }}</td>
            <td>{{ item.count }}</td>
          </tr>
        </tbody>
      </table>
    </div>
    <div class="d-paner-footer">
      <div class="d-paner-actions">
        <button @click="handleAnalyse" class="d-btn d-btn-primary d-actions-item" type="button">元素统计</button>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  components: {

  },

  props: {

  },

  data () {
    return {
      state: {
        list: [],
        total: 0,
        html: 0,
        text: 0
      }
    }
  },

  watch: {

  },

  methods: {
    /**
     * @function 统计
    */
    handleAnalyse () {
      let els = document.getElementsByTagName('*')
      let map = {}
      for (var i = 0; i < els.length; i++) {
        let el = els[i]
        if (!map[el.tagName.toLowerCase()]) {
          map[el.tagName.toLowerCase()] = 1
        } else {
          map[el.tagName.toLowerCase()]++
        }
      }
      let total = 0
      let list = []
      for (let key in map) {
        list.push({
          tagName: key,
          count: map[key]
        })
        total += map[key]
      }
      list = list.sort((a, b) => {
        return a.count > b.count ? -1 : a.count < b.count ? 1 : 0
      })
      this.state.list = list
      this.state.total = total
      // 元素字符
      this.state.html = String(document.documentElement.outerHTML).length
      this.state.text = document.documentElement.outerText.length
    }
  },

  beforeMount () {

  },

  mounted () {

  }
}
</script>

<style lang="less" scoped>

</style>
